#include "wifi.h"
#include "main.h"

_wifi_data wifi_data;



const char*wifi_TEXT[][SYSTEM_LANGUAGE_NUM] =
{
	{ "WIFI未连接", "WIFI未連接", "WiFi Not Connected", NULL},
	{ "WIFI已连接", "WIFI已連接", "WiFi Connected", NULL},
  { "WIFI已断开", "WIFI已斷開", "WiFi Disconnected", NULL},
  { "WIFI连接失败", "WIFI連接失敗", "WiFi connection failed", NULL},
};



static void https_request_by_get_task(void *pvParameters)
{
  int i=0;
  int res;
  int count=0;
  // SYSTEM_State.HuoQu_TianQi_Flag=false;
  // SYSTEM_State.HuoQu_ShiJian_Flag=false;
  // SYSTEM_State.HuoQu_LaoHuangLi_Flag=false;

  //printf("HTTP任务开始等待WIFI连接成功...\r\n");
  //xEventGroupWaitBits(SYSTEM_State.wifi_event_group, BIT0, true, false, portMAX_DELAY);
  while(1)
  {  

    xSemaphoreTake(SYSTEM_State.https_request_Semaphore, portMAX_DELAY);//等待信号量

    count = uxSemaphoreGetCount(SYSTEM_State.https_request_Semaphore);//获取信号的值
    WIFI_DEBUG("计数信号量的值:%d\r\n",count);

    if(SYSTEM_State.wifi_scan_flag==true)
    {
      SYSTEM_State.wifi_scan_flag=2;
      wifi_scan_list_start(); 
      continue ;     
    }



    if(SYSTEM_State.WIFI_Sta!=wifi_yilianjie)
    {
      WIFI_DEBUG("wifi未连接\r\n");
      
      vTaskDelay(1000 / portTICK_PERIOD_MS);
      lvgl_tishi_create(lv_scr_act(),wifi_TEXT[0][SYSTEM_Get_Language()],200,3);
      SYSTEM_State.HuoQu_bilibili_Flag = false;
      SYSTEM_State.HuoQu_ShiJian_Flag = false;
      SYSTEM_State.HuoQu_LaoHuangLi_Flag =false;
      SYSTEM_State.HuoQu_TianQi_Flag =false;
      lvgl_ShuaXin_close();
      continue;
    }

     if(SYSTEM_State.HuoQu_bilibili_Flag == true)
     {
       if(SYSTEM_State.WIFI_Sta==wifi_yilianjie)
       {

        res = https_get_bilibili_fensi();
        if(res==0)
        {

          lvgl_bilibili_Set_fensi(SYSTEM_State.bilibili_Data.fensi);
          lvgl_bilibili_Set_guanzhu(SYSTEM_State.bilibili_Data.guanzhu);         
        }
        //res =  https_get_bilibili_bofang();
        if(res==0)
        {
          lvgl_bilibili_Set_bofang(SYSTEM_State.bilibili_Data.bofang);    
        }        



       }
       SYSTEM_State.HuoQu_bilibili_Flag = false;
     }





    if(SYSTEM_State.HuoQu_ShiJian_Flag==true&&SYSTEM_State.WIFI_Sta==true)
    {
      
      res = HTTP_Get_ShiJian(&SYSTEM_State.RiQi_Data);
      if(res==0)
      {
          
        //if(ZhuJieMian_Data.Fen!=SYSTEM_State.RiQi_Data.fen)
       // {
          ZhuJieMian_Data.Miao = 0;
          ZhuJieMian_Data.Fen = SYSTEM_State.RiQi_Data.fen;
          ZhuJieMian_Data.Shi = SYSTEM_State.RiQi_Data.shi;  
        //}
          WIFI_DEBUG("同步时间: %02d:%02d:%02d\r\n",ZhuJieMian_Data.Shi,ZhuJieMian_Data.Fen,ZhuJieMian_Data.Miao);

      }else
      {
        
      }
      SYSTEM_State.HuoQu_ShiJian_Flag = false;

    }  

    if(SYSTEM_State.HuoQu_LaoHuangLi_Flag==true)
    {
      if(SYSTEM_State.WIFI_Sta==wifi_yilianjie)
      {      
        lvgl_LaoHuangLi_Set_YinLi("正在获取...");
        res = https_get_LaoHuangLi(SYSTEM_State.RiQi_Data.riqi,&SYSTEM_State.laohuangli_data);
        if(res==0)
        {

          lvgl_LaoHuangLi_Set_WuXing(SYSTEM_State.laohuangli_data.wuxing);
          lvgl_LaoHuangLi_Set_ChongSha(SYSTEM_State.laohuangli_data.chongsha);
          lvgl_LaoHuangLi_Set_Yi(SYSTEM_State.laohuangli_data.yi);
          lvgl_LaoHuangLi_Set_Ji(SYSTEM_State.laohuangli_data.ji);
          lvgl_LaoHuangLi_Set_JiShenYiQu(SYSTEM_State.laohuangli_data.jishen);
          lvgl_LaoHuangLi_Set_XiongShenYiJi(SYSTEM_State.laohuangli_data.xiongshen);
          lvgl_LaoHuangLi_Set_YinLi(SYSTEM_State.laohuangli_data.yinli);
          lvgl_LaoHuangLi_Set_YangLi(SYSTEM_State.laohuangli_data.yangli);        


        }else
        {
          
        }

      }else
      {
        lvgl_LaoHuangLi_Set_YinLi("WIFI未连接");

      }

      SYSTEM_State.HuoQu_LaoHuangLi_Flag =false;
    }  
    
    //SYSTEM_State.HuoQu_TianQi_Flag=false;
    if(SYSTEM_State.HuoQu_TianQi_Flag==true)
    {
      lvgl_TianQi_Set_ChengShi("正在获取...");
     // vTaskDelay(10 / portTICK_PERIOD_MS);
      if(SYSTEM_State.WIFI_Sta==wifi_yilianjie)
      {
        res = https_get_TianQi();

        if(res==0)
        {
            //xEventGroupSetBits(SYSTEM_State.TianQi_event_group, BIT0);
          lvgl_TianQi_Set_ChengShi(SYSTEM_State.City);
          lvgl_TianQi_Set_RiChuRiLuo(0,0,0,0,SYSTEM_State.RiLuo_Data[0].sunrise,SYSTEM_State.RiLuo_Data[0].sunset);

            lvgl_TianQi_Set_DangTianQi(
                0,
            atoi(SYSTEM_State.Weather_Data[0].code_day),
            atoi(SYSTEM_State.Weather_Data[0].high),
            SYSTEM_State.Weather_Data[0].text_day,
            atoi(SYSTEM_State.Weather_Data[0].low),
            atoi(SYSTEM_State.Weather_Data[0].high)
            );
            
            lvgl_TianQi_Set_TianQi_JinTian(
            0, 
            atoi(SYSTEM_State.Weather_Data[0].code_day),
            "今天",
            atoi(SYSTEM_State.Weather_Data[0].low),
            atoi(SYSTEM_State.Weather_Data[0].high)
            );

            lvgl_TianQi_Set_TianQi_MingTian(
            0, 
            atoi(SYSTEM_State.Weather_Data[1].code_day),
            "明天",
            atoi(SYSTEM_State.Weather_Data[1].low),
            atoi(SYSTEM_State.Weather_Data[1].high)
            );

            lvgl_TianQi_Set_TianQi_HouTian(
            0, 
            atoi(SYSTEM_State.Weather_Data[2].code_day),           
            "后天",
            atoi(SYSTEM_State.Weather_Data[2].low),
            atoi(SYSTEM_State.Weather_Data[2].high)
            );

            lvgl_TianQi_Set_FengSu(SYSTEM_State.Weather_Data[0].wind_scale);
            lvgl_TianQi_Set_FengXiang(SYSTEM_State.Weather_Data[0].wind_direction);
            lvgl_TianQi_Set_JiangShui(SYSTEM_State.Weather_Data[0].rainfall);
            lvgl_TianQi_Set_ShiDu(SYSTEM_State.Weather_Data[0].humidity);
        }
 
      }else
      {
        lvgl_TianQi_Set_ChengShi("WIFI未连接");

      }
      SYSTEM_State.HuoQu_TianQi_Flag =false;
    }
    lvgl_ShuaXin_close();
    vTaskDelay(10 / portTICK_PERIOD_MS);
  } 
  vTaskDelete(NULL);
}

/** 
 * wifi事件处理函数
 * @param[in]   ctx     :表示传入的事件类型对应所携带的参数
 * @param[in]   event   :表示传入的事件类型
 * @retval      
 *              ESP_OK  : succeed
 *              其他    :失败 
 * @par         修改日志 
 *               Ver0.0.1:
                    Helon_Chan, 2018/06/04, 初始化版本\n 
 */

static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
{
  static int err_code;
  WIFI_DEBUG("消息ID:%d\r\n",event->event_id);
  switch (event->event_id)
  {


    case SYSTEM_EVENT_SCAN_DONE:
      WIFI_DEBUG("扫描结束\r\n");
      wifi_scan_list_get();
      

    break;


    case SYSTEM_EVENT_ETH_STOP:
      WIFI_DEBUG("以太网停止\r\n");
    break;


  case SYSTEM_EVENT_WIFI_READY:
    WIFI_DEBUG("WIFI就绪\r\n");

  break;
  case SYSTEM_EVENT_STA_DISCONNECTED:


    wifi_lianjie_shibai(event);



  break;
   case SYSTEM_EVENT_STA_CONNECTED:
    WIFI_DEBUG("WIFI已连接\r\n");

   // lvgl_tishi_create(lv_scr_act(),wifi_TEXT[1][SYSTEM_Get_Language()],200,3);
    

  break;

  case SYSTEM_EVENT_STA_GOT_IP:

    wifi_lianjie_chenggong(event);



    //ESP_ERROR_CHECK(esp_wifi_disconnect());
    break;
  default:
    break;
  }
  return ESP_OK;

}

static void app_task(void *pvParameters)
{
    uint32_t cnt=0;
    char buf[20];
    while (1)
     {
        cnt++;
        printf("\b\b\b\b\b\b\b\b\b\b\b\b\bRuning...%03d",cnt);
        fflush(stdout); //刷新缓冲区
        vTaskDelay(1000 / portTICK_RATE_MS);
    }
}

static void user_wifi_init(void)
{
  ESP_ERROR_CHECK(nvs_flash_init());
  
  tcpip_adapter_init();
  ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
  wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  // wifi_config_t wifi_config = {
  //     .sta = {
  //         .ssid = "ASKJ",
  //         .password = "12345678",
  //         // .ssid = "Xiaomi_GSM",
  //         // .password = "17625349864",

  //     },
  // };

  nvs_get_wifi(SYSTEM_State.wifi_name,SYSTEM_State.wifi_password);

  wifi_lianjie(SYSTEM_State.wifi_name,SYSTEM_State.wifi_password,NULL);

  // sprintf(wifi_config.sta.ssid,"%s",SYSTEM_State.wifi_name);
  // sprintf(wifi_config.sta.password,"%s",SYSTEM_State.wifi_password);

  // memcpy(wifi_data.wifi_config.sta.ssid,SYSTEM_State.wifi_name,strlen(SYSTEM_State.wifi_name));
  // memcpy(wifi_data.wifi_config.sta.password,SYSTEM_State.wifi_password,strlen(SYSTEM_State.wifi_password));

  // WIFI_DEBUG("wifi名称:%s\r\n",wifi_data.wifi_config.sta.ssid);
  // WIFI_DEBUG("wifi密码:%s\r\n",wifi_data.wifi_config.sta.password);
  // //ESP_ERROR_CHECK(esp_wifi_disconnect());

  // WIFI_DEBUG("启动WIFI...\r\n");
  // ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
  // ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_data.wifi_config));
  // ESP_ERROR_CHECK(esp_wifi_start());
 // ESP_ERROR_CHECK(esp_wifi_connect());

  ESP_ERROR_CHECK(esp_wifi_get_mac(ESP_IF_WIFI_STA,SYSTEM_State.MAC));
  WIFI_DEBUG("MAC:%02x:%02x:%02x:%02x:%02x:%02x\r\n",SYSTEM_State.MAC[0],SYSTEM_State.MAC[1],
  SYSTEM_State.MAC[2],SYSTEM_State.MAC[3],SYSTEM_State.MAC[4],SYSTEM_State.MAC[5]);

  

  

}


int wifi_scan_list_get(void)
{

	uint16_t number = WIFI_SCAN_LIST_SIZE;			// 默认扫描列表大小
	SYSTEM_State.wifi_scan_list_cnt= 0;								// 初始化AP数量0
  WIFI_DEBUG("获取wifi列表...\r\n");  

	ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, SYSTEM_State.wifi_ap_info));// 获取搜索的具体AP信息
	ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&SYSTEM_State.wifi_scan_list_cnt));		//接入点的数量

	WIFI_DEBUG("Total APs scanned = %d\r\n",SYSTEM_State.wifi_scan_list_cnt);
	for (int i = 0; (i < WIFI_SCAN_LIST_SIZE) && (i < SYSTEM_State.wifi_scan_list_cnt); i++) 
  {

		WIFI_DEBUG("wifi名:%s wiif信号强度:%d wifi通道 %d\r\n",  
      SYSTEM_State.wifi_ap_info[i].ssid,
     SYSTEM_State.wifi_ap_info[i].rssi,
     SYSTEM_State.wifi_ap_info[i].primary
    );		
		//WIFI_DEBUG("wiif信号强度:%d ",  SYSTEM_State.wifi_ap_info[i].rssi);		// 打印信号强度	
		// print_auth_mode(ap_info[i].authmode);				// 打印认证方式
		// if (ap_info[i].authmode != WIFI_AUTH_WEP) {
		// 	print_cipher_type(ap_info[i].pairwise_cipher, ap_info[i].group_cipher);
		// }
		//WIFI_DEBUG("wifi通道 %d\r\n", SYSTEM_State.wifi_ap_info[i].primary);
	}
  
  //if(SYSTEM_State.wifi_scan_list_cnt)
  {
    SYSTEM_State.wifi_scan_flag=false;
    esp_wifi_scan_stop();
    lvgl_ShuaXin_close();
  }

  return 0;
}

int wifi_scan_list_start(void)
{

  WIFI_DEBUG("开始扫描wifi列表\r\n");
  ESP_ERROR_CHECK(esp_wifi_scan_start(NULL, false));	// 开始扫描WIFI(默认配置，非阻塞方式)

  return 0;
}

void wifi_init(void)
{

  user_wifi_init();

  WIFI_DEBUG("创建HTTP任务\r\n");
  xTaskCreate(https_request_by_get_task,
              "https_request_by_get_task",
              1024 * 10,
              NULL,
              5,
              NULL);
}


void wifi_lianjie(char *name, char *password, void(*cb)(char * text, void *dat))
{

  wifi_data.cb=cb;

  memset(wifi_data.wifi_config.sta.ssid,0x00,sizeof(wifi_data.wifi_config.sta.ssid));
  memset(wifi_data.wifi_config.sta.password,0x00,sizeof(wifi_data.wifi_config.sta.password));

  memcpy(wifi_data.wifi_config.sta.ssid,name,strlen(name));
  memcpy(wifi_data.wifi_config.sta.password,password,strlen(password));


  WIFI_DEBUG("wifi名称:%s\r\n",wifi_data.wifi_config.sta.ssid);
  WIFI_DEBUG("wifi密码:%s\r\n",wifi_data.wifi_config.sta.password);
  //ESP_ERROR_CHECK(esp_wifi_disconnect());

  if(SYSTEM_State.WIFI_Sta==wifi_yilianjie)
  {

    WIFI_DEBUG("先断开wifi连接\r\n");
    SYSTEM_State.WIFI_Sta=wifi_qingqiuduankai;
    ESP_ERROR_CHECK(esp_wifi_disconnect());
    while(SYSTEM_State.WIFI_Sta!=wifi_yiduankai)
    {

        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
    WIFI_DEBUG("已断开\r\n");
  }

  WIFI_DEBUG("连接WIFI...\r\n");
  ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
  ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_data.wifi_config));
  ESP_ERROR_CHECK(esp_wifi_start());
  ESP_ERROR_CHECK(esp_wifi_connect());


  SYSTEM_State.WIFI_Sta = wifi_lianjiehzong;

}

void wifi_lianjie_chenggong(system_event_t *event)
{

    WIFI_DEBUG("WIFI已获取IP\r\n");

    struct in_addr *inaddr;
    char *str;
    inaddr = &event->event_info.got_ip.ip_info.ip;

    str = inet_ntoa(*inaddr);
    WIFI_DEBUG( "IP: %s", str);

    sprintf(SYSTEM_State.ip,"%s",str);

    inaddr = &event->event_info.got_ip.ip_info.netmask;
    str = inet_ntoa(*inaddr);
    WIFI_DEBUG( "子网掩码: %s", str);

    sprintf(SYSTEM_State.ziwangyanma,"%s",str);

    inaddr = &event->event_info.got_ip.ip_info.gw;
    str = inet_ntoa(*inaddr);
    WIFI_DEBUG( "默认网关: %s", str);

    sprintf(SYSTEM_State.wangguan,"%s",str);


    char buf[100];
    sprintf(buf,"%s %s %s",wifi_TEXT[1][SYSTEM_Get_Language()],SYSTEM_State.wifi_name,SYSTEM_State.ip);
    lvgl_tishi_create(lv_scr_act(),buf,200,20);


    SYSTEM_State.WIFI_Sta = wifi_yilianjie;



    memcpy(SYSTEM_State.wifi_name,wifi_data.wifi_config.sta.ssid,sizeof(wifi_data.wifi_config.sta.ssid));
    memcpy(SYSTEM_State.wifi_password,wifi_data.wifi_config.sta.password,sizeof(wifi_data.wifi_config.sta.password));


    nvs_set_wifi(SYSTEM_State.wifi_name,SYSTEM_State.wifi_password);

    SYSTEM_State.HuoQu_ShiJian_Flag=true;//同步一次时间
    xSemaphoreGive(SYSTEM_State.https_request_Semaphore);//释放信号量  

    start_webserver();

    if(wifi_data.cb!=NULL)
    {
      wifi_data.cb(NULL,&SYSTEM_State.WIFI_Sta);

    }
    
}
void wifi_lianjie_shibai(system_event_t *event)
{
    WIFI_DEBUG("WIFI已断开\r\n");
    
    stop_webserver();
    //WIFI_DEBUG("启动重连\r\n");
    //ESP_ERROR_CHECK(esp_wifi_connect());

  if(SYSTEM_State.WIFI_Sta==wifi_qingqiuduankai)
  {


    SYSTEM_State.WIFI_Sta = wifi_yiduankai;
    lvgl_tishi_create(lv_scr_act(),wifi_TEXT[2][SYSTEM_Get_Language()],200,3);
  }else
  {
    SYSTEM_State.WIFI_Sta = wifi_lianjieshibai;

    lvgl_tishi_create(lv_scr_act(),wifi_TEXT[3][SYSTEM_Get_Language()],200,3);

    if(wifi_data.cb!=NULL)
    {
      wifi_data.cb(NULL,&SYSTEM_State.WIFI_Sta);

    }

  }



}
